<template>
  <div class="page page_knowledge w100 h100 radius8">
    <div class="search_area">
      <div class="search_form">
        <el-row :gutter="40">
          <el-col :span="4">
            <label>分类：</label>
            <el-select v-model="search.type" clearable placeholder="请选择">
              <el-option
                v-for="o in typeOptions"
                :key="o.value"
                :label="o.label"
                :value="o.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <label>标题：</label>
            <el-input v-model="search.title" />
          </el-col>
        </el-row>
      </div>
      <div class="search_btn_group">
        <el-button class="btn_search" type="primary" plain @click="handleSearch"> 查询 </el-button>
        <el-button class="btn_search" type="primary" plain @click="handleReset"> 重置 </el-button>
        <el-button
          type="primary"
          v-if="authority"
          class="btn_append"
          @click="handleClickAdd"
        >
          新增
        </el-button>
      </div>
    </div>
    <div class="knowledgeList" v-if="knowledgeList.length > 0">
      <div
        class="item"
        v-for="o in knowledgeList"
        :key="o.id"
        @click="getDetail(o)"
      >
        <div class="top">
          <div class="type">{{ o.type === "other" ? "其他" : o.type }}</div>
          <div class="lastUpdate">
            {{ $moment(o.updateTime || o.createTime).format("yyyy-MM-DD") }}
          </div>
        </div>
        <div class="bottom">
          <div class="title">{{ o.title }}</div>
          <div class="btn-icon-group" v-if="authority">
            <!-- <el-tooltip content="查看">
              <el-icon size="18px" color="#409eff" @click="handleView(o)"
                ><View
              /></el-icon>
            </el-tooltip> -->
            <el-tooltip content="编辑">
              <el-icon size="18px" color="#409eff" @click.stop="handleEdit(o)"
                ><Edit
              /></el-icon>
            </el-tooltip>
            <el-tooltip content="删除">
              <el-icon size="18px" color="#f56c6c" @click.stop="handleDelete(o)"
                ><Delete
              /></el-icon>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
    <el-empty description="暂无数据" v-else />
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      width="85vw"
      top="10vh"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        v-if="dialogVisible"
        :model="form"
        :rules="rules"
        label-width="80px"
        :size="formSize"
      >
        <el-form-item label="分类：" prop="type">
          <el-select
            v-model="form.type"
            :disabled="openType === 'view'"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="o in typeOptions"
              :key="o.value"
              :label="o.label"
              :value="o.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="form.title"
            :disabled="openType === 'view'"
            clearable
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="内容：" prop="html">
          <editor
            v-model="form.html"
            height="60vh"
            :disabled="openType === 'view'"
            ref="editorRef"
          />
        </el-form-item>
      </el-form>
      <template #footer v-if="openType !== 'view'">
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleCreate"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import editor from "./components/editor.vue"
import {
  getKnowledgeList,
  postKnowledgeCreate,
  postKnowledgeSearch,
  postKnowledgeUpdate,
  postKnowledgeDelete
} from "@/api/blog/knowledge"

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Knowledge",
  props: {},
  components: { editor },
  emit: [],

  data() {
    const validateHtml = (rule, value, callback) => {
      if (this.$refs.editorRef?.editorRef?.isEmpty() || value === "") {
        callback(new Error("请输入内容"))
      } else {
        callback()
      }
    }

    return {
      dialogVisible: false,
      openType: "create",
      formSize: "default",
      search: {
        type: "",
        title: ""
      },
      form: {
        type: "",
        title: "",
        html: ""
      },
      rules: {
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { max: 32, message: "最多仅可输入32位字符", trigger: "blur" }
        ],
        html: [{ required: true, validator: validateHtml, trigger: "blur" }]
      },
      knowledgeList: [],
      cur: {}
    }
  },
  computed: {
    dialogTitle() {
      const titleReflect = {
        create: "新增",
        view: "查看",
        edit: "编辑"
      }
      return titleReflect[this.openType]
    },
    typeOptions() {
      return [
        {
          label: "html",
          value: "html"
        },
        {
          label: "css",
          value: "css"
        },
        {
          label: "javaScript",
          value: "javaScript"
        },
        {
          label: "vue",
          value: "vue"
        },
        {
          label: "react",
          value: "react"
        },
        {
          label: "uniApp",
          value: "uniApp"
        },
        {
          label: "wxApplet",
          value: "wxApplet"
        },
        {
          label: "node.js",
          value: "node.js"
        },
        {
          label: "其他",
          value: "other"
        }
      ]
    },
    userRole() {
      return this.$store.getters['user/userRole']
    },
    authority() {
      return this.userRole === "admin"
    }
  },
  watch: {
    "form.type": {
      handler(nv) {
        if (nv && this.openType === "create") {
          this.$refs.formRef.clearValidate("type")
        }
      },
      immediate: false
    },
    "form.html": {
      handler(nv) {
        if (
          !this.$refs.editorRef?.editorRef?.isEmpty() &&
          nv !== "" &&
          this.openType === "create"
        ) {
          this.$refs.formRef.clearValidate("html")
        }
      },
      immediate: false
    }
  },
  methods: {
    handleClickAdd() {
      this.openType = "create"
      this.dialogVisible = true
    },

    handleCreate() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.openType === "create") {
            this.postKnowledgeCreate()
          } else {
            this.postKnowledgeUpdate()
          }
        }
      })
    },

    handleClose() {
      this.$refs.formRef.resetFields()
      Object.assign(this.form, { type: "", title: "", html: "" })
      this.dialogVisible = false
    },

    async getKnowledgeList() {
      const { code, data, msg } = await getKnowledgeList()
      if (code === 200) {
        this.knowledgeList = data
      } else {
        this.knowledgeList = []
        this.$message.error(msg)
      }
    },

    async handleSearch() {
      const { type, title } = this.search
      const { code, data, msg } = await postKnowledgeSearch({
        type: type === "all" ? "" : type,
        title:title.trim()
      })
      if (code === 200) {
        this.knowledgeList = data
      } else {
        this.knowledgeList = []
        this.$message.error(msg)
      }
    },

    handleReset() {
      Object.assign(this.search, { type: "", title: "" })
      this.getKnowledgeList()
    },

    async postKnowledgeCreate() {
      const { code, msg } = await postKnowledgeCreate(this.form)
      if (code === 200) {
        this.$message.success("新增成功！")
        this.getKnowledgeList()
        this.handleClose()
      } else {
        this.$message.error(msg)
      }
    },

    async postKnowledgeUpdate() {
      const { code, msg } = await postKnowledgeUpdate({
        id: this.cur.id,
        ...this.form
      })
      if (code === 200) {
        this.$message.success("编辑成功！")
        this.getKnowledgeList()
        this.handleClose()
      } else {
        this.$message.error(msg)
      }
    },

    // handleView(item) {
    //   this.dialogVisible = true
    //   this.openType = "view"
    //   const { type, title, html } = item
    //   Object.assign(this.form, { type, title, html })
    // },

    handleEdit(item) {
      this.cur = item
      this.dialogVisible = true
      this.openType = "edit"
      const { type, title, html } = item
      Object.assign(this.form, { type, title, html })
    },

    handleDelete(item) {
      const { id } = item
      this.$messageBox
        .confirm("是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.postKnowledgeDelete(id)
        })
    },

    async postKnowledgeDelete(id) {
      const { code, msg } = await postKnowledgeDelete({ id })
      if (code === 200) {
        this.getKnowledgeList()
      } else {
        this.$message.error(msg)
      }
    },

    getDetail(item) {
      this.$router.push({
        path: "/knowledge/detail",
        query: { html: item.html }
      })
    }
  },
  created() {},
  mounted() {
    this.getKnowledgeList()
    console.log(this.$store);
  }
}
</script>

<style lang="scss" scoped>
.page_knowledge {
  position: relative;
  .search_area {
    display: flex;
    justify-content: space-between;
    padding-bottom: 16px;
    border-bottom: 1px solid $border;
    .search_form {
      flex: 1;
      .el-col {
        display: flex;
        align-items: center;
        color: $primary_text;
        label {
          flex-shrink: 0;
          width: fit-content;
        }
      }
    }
  }
  .knowledgeList {
    height: calc(100% - 50px);
    padding-top: 16px;
    .item {
      position: relative;
      padding: 12px;
      margin-bottom: 16px;
      box-shadow: 0 0 6px 2px $shadow;
      .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        .type {
          margin-right: 12px;
          font-size: 24px;
        }
      }
      .bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .btn-icon-group {
          .el-icon {
            cursor: pointer;
            &:nth-child(2) {
              margin: 0 16px;
            }
          }
        }
      }
    }
  }
}
</style>
